//给定一个二叉树，找出其最小深度。 
//
// 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 
//
// 说明：叶子节点是指没有子节点的节点。 
//
// 
//
// 示例 1： 
//
// 
//输入：root = [3,9,20,null,null,15,7]
//输出：2
// 
//
// 示例 2： 
//
// 
//输入：root = [2,null,3,null,4,null,5,null,6]
//输出：5
// 
//
// 
//
// 提示： 
//
// 
// 树中节点数的范围在 [0, 10⁵] 内 
// -1000 <= Node.val <= 1000 
// 
// Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 577 👎 0


package leetcode.editor.cn1;

import com.leetcode.entity.TreeNode;

import java.util.Stack;

//Java：二叉树的最小深度
public class MinimumDepthOfBinaryTree {
    public static void main(String[] args) {
        Solution solution = new MinimumDepthOfBinaryTree().new Solution();
        // TO TEST
        TreeNode node = new TreeNode(3);
        node.left = new TreeNode(9);
        node.right = new TreeNode(20);
        node.right.left = new TreeNode(15);
        node.right.right = new TreeNode(7);
        System.out.println(solution.minDepth(node));

        TreeNode node2 = new TreeNode(1);
        node2.left = new TreeNode(2);
        node2.right = new TreeNode(3);
        node2.left.left = new TreeNode(4);
        node2.left.right = new TreeNode(5);
        System.out.println(solution.minDepth(node2));
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        /**
         * 要到达叶子节点
         * @param root
         * @return
         */
        int min = Integer.MAX_VALUE;
        public int minDepth(TreeNode root) {
            if (root == null)
                return 0;
            Stack<Integer> stack = new Stack<>();
            dfs(root, stack);
            return min;
        }

        public void dfs(TreeNode node, Stack<Integer> stack) {
            if (node == null)
                return;
            stack.push(node.val);
            if (node.left == null&& node.right == null) {
                // 只有叶子节点才进行计算
                min = Math.min(min, stack.size());
                stack.pop();
                return;
            }
            dfs(node.left, stack);
            dfs(node.right, stack);
            stack.pop();
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
